<template>
  <tn-navbar :bottom-shadow="false" fixed>
    <text class="title">消息详情</text>
  </tn-navbar>
  <view class="container">
    <!-- 加载状态 -->
    <view class="loading-container" v-if="loading">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>

    <template v-else>
      <!-- 状态提示条 -->
      <view class="status-bar" :class="'status-' + data.status">
        <view class="status-icon">
          <tn-icon :name="getStatusIcon(data.status)" size="40" color="#fff"></tn-icon>
        </view>
        <view class="status-info">
          <text class="status-text">{{ getStatusText(data.status) }}</text>
          <text class="status-desc" v-if="data.status < 2">请尽快回复车主</text>
          <text class="status-desc" v-else>{{ getStatusDesc(data.status) }}</text>
        </view>
      </view>

      <!-- 车辆信息和备注信息卡片 -->
      <view class="card info-card">
        <view class="vehicle-info">
          <text class="license-plate">{{ data.vehicles?.license_plate }}</text>
          <view class="urgency-tag" :class="'urgency-' + data.urgency_status">
            {{ data.urgency_status_text || getUrgencyText(data.urgency_status) }}
          </view>
        </view>
        
        <view class="notes-section" v-if="data.notes">
          <view class="section-divider"></view>
          <text class="notes-label">备注信息</text>
          <text class="notes-text">{{ data.notes }}</text>
        </view>
      </view>
      
      <!-- 快捷回复区域 -->
      <view class="card quick-reply-card" v-if="data.status < 2">
        <view class="card-header">
          <text class="card-title">快捷回复</text>
        </view>
        <view class="card-content">
          <view class="quick-reply-tags">
            <view 
              v-for="(tag, index) in quickReplyTags" 
              :key="index"
              class="quick-reply-tag"
              @tap="selectQuickReply(tag)"
            >{{ tag }}</view>
          </view>
          
          <view class="reply-input-area">
            <input 
              class="reply-input" 
              v-model="replyContent" 
              placeholder="请输入回复内容..." 
              confirm-type="send"
              @confirm="sendReply"
            />
            <button class="reply-btn" @tap="sendReply" :disabled="!replyContent">发送</button>
          </view>
        </view>
      </view>
      
      <!-- 消息记录 -->
      <view class="card message-card">
        <view class="card-header">
          <text class="card-title">消息记录</text>
          <text class="message-time">{{ data.itime }}</text>
        </view>
        
        <view class="card-content">
          <scroll-view 
            class="message-list" 
            scroll-y 
            :scroll-into-view="'msg-' + (data.msgLog?.length || 0)"
          >
            <view v-if="!data.msgLog || data.msgLog.length === 0" class="empty-message">
              <text class="empty-text">暂无消息记录</text>
            </view>
            <view 
              v-else
              v-for="(msg, index) in data.msgLog" 
              :key="msg.id"
              :id="'msg-' + (index + 1)"
              class="message-item"
              :class="{
                'system-message': msg.type === 0,
                'user-message': msg.type === 1,
                'self-message': isCurrentUser(msg)
              }"
            >
              <view class="message-sender" v-if="!isCurrentUser(msg)">{{ getSenderName(msg) }}</view>
              <view class="message-sender self-sender" v-else>{{ getSenderName(msg) }}</view>
              <view class="message-bubble">
                <text class="message-content">{{ msg.content }}</text>
              </view>
              <text class="message-time-small">{{ formatTime(msg.itime) }}</text>
            </view>
          </scroll-view>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="action-buttons">
        <button 
          class="primary-btn"
          v-if="data.status < 3"
          @tap="handleComplete"
        >完成挪车</button>
        <button
            v-if="!data.is_black"
          class="warning-btn"
          @tap="handleBlacklist"
        >拉黑车主</button>
      </view>
    </template>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';

const data = ref({});
const loading = ref(true);
const replyContent = ref('');

// 快捷回复选项
const quickReplyTags = [
  '马上过去',
  '5分钟后到',
  '10分钟后到',
  '正在处理',
  '已在路上',
  '请稍等片刻',
  '收到，马上挪车',
  '不好意思，马上挪走'
];

// 选择快捷回复
const selectQuickReply = (tag) => {
  replyContent.value = tag;
};

// 获取页面参数
onMounted(() => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options;
  if (options.id) {
    getMessageDetail(options.id);
  }
});

// 添加模拟数据 - 包含不同状态的消息详情
const mockMessageDetails = {
  // 状态0: 处理中
  "92": {
    code: 200,
    msg: "success",
    data: {
      id: 92,
      user_id: 14,
      qrcode_id: 10,
      qrcode_user_id: 12,
      urgency_status: 0,
      notes: "影响通行，挡住出口，维修需要",
      status: 0,
      update_time: "2025-03-21 13:48:20",
      instime: 1742188332,
      itime: "2025-03-17 13:12:12",
      vehicles: {
        license_plate: "苏Y665557",
        remark: ""
      },
      msgLog: [
        {
          id: 337,
          vr_id: 92,
          user_id: 14,
          type: 1,
          message_type: 1,
          content: "呼叫挪车",
          instime: 1742188332,
          itime: "2025-03-17 13:12:12"
        },
        {
          id: 338,
          vr_id: 92,
          user_id: 14,
          type: 1,
          message_type: 2,
          content: "需要外出",
          instime: 1742188332,
          itime: "2025-03-17 13:12:12"
        }
      ],
      qrcodeCode: {
        code: "clIQvaSZ"
      },
      urgency_status_text: "普通:不急，希望车主看到后尽快处理",
      is_black: false
    }
  },
  // 状态1: 通知已发送
  "93": {
    code: 200,
    msg: "success",
    data: {
      id: 93,
      user_id: 14,
      qrcode_id: 10,
      qrcode_user_id: 12,
      urgency_status: 1,
      notes: "紧急情况，需要立即挪车",
      status: 1,
      update_time: "2025-03-19 14:05:20",
      instime: 1742364143,
      itime: "2025-03-19 14:02:23",
      vehicles: {
        license_plate: "苏A88888",
        remark: "黑色SUV"
      },
      msgLog: [
        {
          id: 339,
          vr_id: 93,
          user_id: 14,
          type: 1,
          message_type: 1,
          content: "紧急呼叫挪车",
          instime: 1742364143,
          itime: "2025-03-19 14:02:23"
        },
        {
          id: 340,
          vr_id: 93,
          user_id: 0,
          type: 0,
          message_type: 0,
          content: "系统已发送通知给车主",
          instime: 1742364200,
          itime: "2025-03-19 14:03:20"
        }
      ],
      qrcodeCode: {
        code: "clIQvaSZ"
      },
      urgency_status_text: "紧急:情况紧急，请尽快处理",
      is_black: false
    }
  },
  // 状态2: 已回复
  "94": {
    code: 200,
    msg: "success",
    data: {
      id: 94,
      user_id: 14,
      qrcode_id: 10,
      qrcode_user_id: 12,
      urgency_status: 0,
      notes: "影响通行，挡住出口，维修需要",
      status: 2,
      update_time: "2025-03-19 15:20:20",
      instime: 1742368661,
      itime: "2025-03-19 15:17:41",
      vehicles: {
        license_plate: "京A12345",
        remark: "白色轿车"
      },
      msgLog: [
        {
          id: 341,
          vr_id: 94,
          user_id: 14,
          type: 1,
          message_type: 1,
          content: "呼叫挪车",
          instime: 1742368661,
          itime: "2025-03-19 15:17:41"
        },
        {
          id: 342,
          vr_id: 94,
          user_id: 0,
          type: 0,
          message_type: 0,
          content: "系统已发送通知给车主",
          instime: 1742368700,
          itime: "2025-03-19 15:18:20"
        },
        {
          id: 343,
          vr_id: 94,
          user_id: 12,
          type: 1,
          message_type: 2,
          content: "抱歉，我马上过来挪车",
          instime: 1742368800,
          itime: "2025-03-19 15:20:00"
        }
      ],
      qrcodeCode: {
        code: "clIQvaSZ"
      },
      urgency_status_text: "普通:不急，希望车主看到后尽快处理",
      is_black: false
    }
  },
  // 状态3: 已完成
  "96": {
    code: 200,
    msg: "success",
    data: {
      id: 96,
      user_id: 14,
      qrcode_id: 10,
      qrcode_user_id: 12,
      urgency_status: 0,
      notes: "需要外出",
      status: 3,
      update_time: "2025-03-21 14:15:20",
      instime: 1742536184,
      itime: "2025-03-21 13:49:44",
      vehicles: {
        license_plate: "粤B99999",
        remark: "红色跑车"
      },
      msgLog: [
        {
          id: 344,
          vr_id: 96,
          user_id: 14,
          type: 1,
          message_type: 1,
          content: "呼叫挪车",
          instime: 1742536184,
          itime: "2025-03-21 13:49:44"
        },
        {
          id: 345,
          vr_id: 96,
          user_id: 0,
          type: 0,
          message_type: 0,
          content: "系统已发送通知给车主",
          instime: 1742536200,
          itime: "2025-03-21 13:50:00"
        },
        {
          id: 346,
          vr_id: 96,
          user_id: 12,
          type: 1,
          message_type: 2,
          content: "收到，马上过来",
          instime: 1742536300,
          itime: "2025-03-21 13:51:40"
        },
        {
          id: 347,
          vr_id: 96,
          user_id: 0,
          type: 0,
          message_type: 0,
          content: "挪车请求已完成",
          instime: 1742536520,
          itime: "2025-03-21 13:55:20"
        }
      ],
      qrcodeCode: {
        code: "clIQvaSZ"
      },
      urgency_status_text: "普通:不急，希望车主看到后尽快处理",
      is_black: false
    }
  },
  // 状态4: 通知失败
  "97": {
    code: 200,
    msg: "success",
    data: {
      id: 97,
      user_id: 14,
      qrcode_id: 10,
      qrcode_user_id: 12,
      urgency_status: 0,
      notes: "挡住出口，影响通行，其他原因",
      status: 4,
      update_time: "2025-03-21 20:04:03",
      instime: 1742558603,
      itime: "2025-03-21 20:03:23",
      vehicles: {
        license_plate: "沪C77777",
        remark: "蓝色MPV"
      },
      msgLog: [
        {
          id: 348,
          vr_id: 97,
          user_id: 14,
          type: 1,
          message_type: 1,
          content: "呼叫挪车",
          instime: 1742558603,
          itime: "2025-03-21 20:03:23"
        },
        {
          id: 349,
          vr_id: 97,
          user_id: 0,
          type: 0,
          message_type: 0,
          content: "通知发送失败，请检查通知设置",
          instime: 1742558643,
          itime: "2025-03-21 20:04:03"
        }
      ],
      qrcodeCode: {
        code: "clIQvaSZ"
      },
      urgency_status_text: "普通:不急，希望车主看到后尽快处理",
      is_black: false
    }
  }
};

// 获取消息详情
const getMessageDetail = async (id) => {
  loading.value = true;
  try {
    // 使用模拟数据替代API调用
    setTimeout(() => {
      // 根据ID获取对应状态的模拟数据
      const mockData = mockMessageDetails[id] || mockMessageDetails["92"];
      data.value = mockData.data;
      console.log('模拟消息详情数据:', data.value);
      loading.value = false;
    }, 300);
  } catch (error) {
    console.error('获取消息详情失败:', error);
    uni.showToast({
      title: '获取消息详情失败',
      icon: 'none'
    });
    loading.value = false;
  }
};

// 获取状态图标
const getStatusIcon = (status) => {
  const iconMap = {
    0: 'time',
    1: 'notification',
    2: 'message',
    3: 'success',
    4: 'close'
  };
  return iconMap[status] || 'info';
};

// 获取紧急程度文本
const getUrgencyText = (urgencyStatus) => {
  const urgencyMap = {
    0: '普通',
    1: '紧急',
    2: '非常紧急'
  };
  return urgencyMap[urgencyStatus] || '普通';
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '处理中',
    1: '通知已发送',
    2: '已回复',
    3: '已完成',
    4: '通知失败'
  };
  return statusMap[status] || '未知状态';
};

// 获取状态描述
const getStatusDesc = (status) => {
  const descMap = {
    2: '车主已回复，请查看消息记录',
    3: '挪车请求已完成',
    4: '通知发送失败，请检查通知设置'
  };
  return descMap[status] || '';
};

// 获取发送者名称
const getSenderName = (msg) => {
  if (msg.type === 0) {
    return '系统';
  } else {
    // 判断是否是当前用户
    const currentUserId = data.value.qrcode_user_id;
    if (msg.user_id.toString() == currentUserId) {
      return '我';
    } else if (msg.user_id === data.value.user_id) {
      return '请求者#' + data.value.user_id;
    } else {
      return '用户';
    }
  }
};

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return '';
  // 只保留时间部分
  const parts = timeStr.split(' ');
  if (parts.length > 1) {
    return parts[1];
  }
  return timeStr;
};

// 回复消息
const handleReply = () => {
  uni.showModal({
    title: '回复',
    editable: true,
    placeholderText: '请输入回复内容',
    success: (res) => {
      if (res.confirm && res.content) {
        sendReply(res.content);
      }
    }
  });
};

// 发送回复
const sendReply = async () => {
  if (!replyContent.value && !event?.detail?.value) {
    uni.showToast({
      title: '请输入回复内容',
      icon: 'none'
    });
    return;
  }
  
  const content = replyContent.value || event.detail.value;
  
  // 使用模拟数据
  uni.showLoading({
    title: '发送中...'
  });
  
  // 模拟API调用延迟
  setTimeout(() => {
    // 添加新消息到消息记录
    if (data.value && data.value.msgLog) {
      const newMsg = {
        id: data.value.msgLog.length + 350,
        vr_id: data.value.id,
        user_id: data.value.qrcode_user_id,
        type: 1,
        message_type: 2,
        content: content,
        instime: Math.floor(Date.now() / 1000),
        itime: new Date().toISOString().replace('T', ' ').substring(0, 19)
      };
      data.value.msgLog.push(newMsg);
      
      // 更新状态为已回复
      data.value.status = 2;
    }
    
    uni.hideLoading();
    uni.showToast({
      title: '回复成功',
      icon: 'success'
    });
    
    // 清空输入框
    replyContent.value = '';
  }, 500);
};

// 完成挪车
const handleComplete =  () => {
  uni.showModal({
    title: '确认完成',
    content: '确认该挪车请求已完成？',
    success: (res) => {
      if (res.confirm) {
        completeRequest();
      }
    }
  });
};

const completeRequest = async () => {
  uni.showLoading({
    title: '处理中...'
  });
  
  // 模拟API调用延迟
  setTimeout(() => {
    // 添加系统消息
    if (data.value && data.value.msgLog) {
      const newMsg = {
        id: data.value.msgLog.length + 350,
        vr_id: data.value.id,
        user_id: 0,
        type: 0,
        message_type: 0,
        content: "挪车请求已完成",
        instime: Math.floor(Date.now() / 1000),
        itime: new Date().toISOString().replace('T', ' ').substring(0, 19)
      };
      data.value.msgLog.push(newMsg);
      
      // 更新状态为已完成
      data.value.status = 3;
    }
    
    uni.hideLoading();
    uni.showToast({
      title: '已标记为完成',
      icon: 'success'
    });
  }, 500);
};

// 拉黑车主
const handleBlacklist = () => {
  uni.showModal({
    title: '确认拉黑',
    content: '确定要将该车主拉入黑名单吗？拉黑后将不再接收该车主的消息。',
    confirmColor: '#ff4d4f',
    success: (res) => {
      if (res.confirm) {
        addToBlacklist();
      }
    }
  });
};

const addToBlacklist = async () => {
  uni.showLoading({
    title: '处理中...'
  });
  
  // 模拟API调用延迟
  setTimeout(() => {
    // 更新拉黑状态
    if (data.value) {
      data.value.is_black = true;
    }
    
    uni.hideLoading();
    uni.showToast({
      title: '已拉黑该车主',
      icon: 'success'
    });
  }, 500);
};

// 判断是否是当前用户发送的消息
const isCurrentUser = (msg) => {
  if (msg.type === 0) return false; // 系统消息
  const currentUserId = data.value.qrcode_user_id;
  return msg.user_id.toString() == currentUserId;
};
</script>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 40rpx;
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400rpx;
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 6rpx solid #f3f3f3;
  border-top: 6rpx solid #1aad19;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #999;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 状态提示条 */
.status-bar {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  border-radius: 12rpx;
  margin-bottom: 30rpx;
  color: #fff;
  
  &.status-0 {
    background: linear-gradient(135deg, #1890ff, #36cfc9);
  }
  
  &.status-1 {
    background: linear-gradient(135deg, #fa8c16, #faad14);
  }
  
  &.status-2 {
    background: linear-gradient(135deg, #52c41a, #73d13d);
  }
  
  &.status-3 {
    background: linear-gradient(135deg, #13c2c2, #36cfc9);
  }
  
  &.status-4 {
    background: linear-gradient(135deg, #f5222d, #ff7875);
  }
}

.status-icon {
  margin-right: 20rpx;
}

.status-info {
  flex: 1;
}

.status-text {
  font-size: 32rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 6rpx;
}

.status-desc {
  font-size: 24rpx;
  opacity: 0.9;
}

/* 卡片通用样式 */
.card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.card-title {
  font-size: 30rpx;
  font-weight: 500;
  color: #333;
}

.card-content {
  padding: 10rpx 0;
}

/* 车辆信息和备注信息卡片 */
.info-card {
  padding: 24rpx 30rpx;
}

.vehicle-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.license-plate {
  font-size: 40rpx;
  font-weight: bold;
  color: #333;
  display: block;
  letter-spacing: 2rpx;
  margin-bottom: 16rpx;
}

.urgency-tag {
  padding: 6rpx 24rpx;
  border-radius: 100rpx;
  font-size: 24rpx;
  font-weight: bold;
  display: inline-block;
  max-width: 100%;
  text-align: center;
  
  &.urgency-0 {
    background-color: #e8f5e9;
    color: #1aad19;
  }
  
  &.urgency-1 {
    background-color: #fff7e6;
    color: #fa8c16;
  }
  
  &.urgency-2 {
    background-color: #fff1f0;
    color: #ff4d4f;
  }
}

.section-divider {
  height: 1rpx;
  background-color: #f0f0f0;
  margin: 20rpx 0;
}

.notes-section {
  margin-top: 10rpx;
}

.notes-label {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 10rpx;
  display: block;
}

.notes-text {
  font-size: 28rpx;
  color: #333;
  line-height: 1.5;
}

/* 快捷回复卡片 */
.quick-reply-card {
  background-color: #f9fcff;
  border: 1rpx solid #e1f3ff;
}

.quick-reply-tags {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 20rpx;
}

.quick-reply-tag {
  padding: 12rpx 24rpx;
  background-color: #fff;
  color: #333;
  font-size: 26rpx;
  border-radius: 100rpx;
  margin-right: 20rpx;
  margin-bottom: 16rpx;
  transition: all 0.2s;
  border: 1rpx solid #e8e8e8;
  
  &:active {
    background-color: #e1f3ff;
    color: #1890ff;
    border-color: #1890ff;
    transform: scale(0.95);
  }
}

.reply-input-area {
  display: flex;
  align-items: center;
  margin-top: 10rpx;
}

.reply-input {
  flex: 1;
  height: 80rpx;
  background-color: #fff;
  border: 1rpx solid #e8e8e8;
  border-radius: 40rpx;
  padding: 0 30rpx;
  font-size: 28rpx;
  margin-right: 20rpx;
}

.reply-btn {
  width: 140rpx;
  height: 80rpx;
  background-color: #1aad19;
  color: #fff;
  border-radius: 40rpx;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  
  &[disabled] {
    opacity: 0.6;
    background-color: #1aad19;
    color: #fff;
  }
}

/* 消息记录卡片 */
.message-time {
  font-size: 24rpx;
  color: #999;
}

.message-list {
  max-height: 400rpx; /* 减小高度 */
}

.empty-message {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 120rpx;
}

.empty-text {
  font-size: 26rpx;
  color: #999;
}

.message-item {
  margin-bottom: 20rpx;
  position: relative;
  
  &.self-message {
    text-align: right;
    
    .message-sender {
      text-align: right;
    }
    
    .message-bubble {
      background-color: #d4f3d9;
      border-radius: 12rpx 0 12rpx 12rpx;
      margin-left: auto;
    }
    
    .message-content {
      color: #1aad19;
    }
    
    .message-time-small {
      text-align: right;
    }
  }
}

.message-sender {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 6rpx;
  
  &.self-sender {
    color: #1aad19;
  }
}

.message-bubble {
  padding: 12rpx 16rpx;
  border-radius: 8rpx;
  max-width: 80%;
  display: inline-block;
}

.system-message {
  .message-sender {
    text-align: center;
    color: #999;
  }
  
  .message-bubble {
    background-color: #f5f5f5;
    margin: 0 auto;
    text-align: center;
    display: block;
  }
  
  .message-content {
    color: #666;
    font-size: 24rpx;
  }
  
  .message-time-small {
    text-align: center;
    display: block;
  }
}

.user-message:not(.self-message) {
  .message-bubble {
    background-color: #e1f3ff;
    border-radius: 0 12rpx 12rpx 12rpx;
  }
  
  .message-content {
    color: #333;
    font-size: 26rpx;
    line-height: 1.4;
  }
}

.message-time-small {
  font-size: 20rpx;
  color: #999;
  margin-top: 6rpx;
  display: block;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  flex-direction: column;
  margin-top: 20rpx;
}

.primary-btn,
.secondary-btn {
  width: 100%;
  height: 88rpx;
  border-radius: 44rpx;
  font-size: 30rpx;
  font-weight: 500;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.primary-btn {
  background-color: #1aad19;
  color: #fff;
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.98);
    opacity: 0.9;
  }
}

.secondary-btn {
  background-color: #f0f0f0;
  color: #ff4d4f;
  
  &:active {
    background-color: #e8e8e8;
  }
}

.warning-btn {
  width: 100%;
  height: 88rpx;
  border-radius: 44rpx;
  font-size: 30rpx;
  font-weight: 500;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff7e6;
  color: #fa8c16;
  border: 1rpx solid #ffd591;
  
  &:active {
    background-color: #fff1e6;
    transform: scale(0.98);
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
</style> 